package com.gxc.controller;

import com.gxc.dao.jpa.UserRepository;
import com.gxc.entity.User;
import com.gxc.service.UserService;
import com.gxc.utils.RestControllerResult;
import java.util.List;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 查询用户列表.
 *
 * @author 宫新程
 * @since 2018/12/15 2:09 PM
 */
@Slf4j
@RestController
public class UserController {

  @Resource private UserService userService;
  @Resource private UserRepository userRepository;

  /** 查询用户列表. */
  @PostMapping("/index")
  public RestControllerResult<Page<User>> userList(
      @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
      @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
    Page<User> pageInfo = userService.findAll(pageNum, pageSize);
    log.info("查询列表成功！总条数：{}，总页数：{}", pageInfo.getTotalElements(), pageInfo.getTotalPages());
    RestControllerResult<Page<User>> result = new RestControllerResult<>();
    result.setSuccess(true);
    result.setData(pageInfo);
    return result;
  }

  @GetMapping("/deleteAll")
  public RestControllerResult<Boolean> deleteAll() {
    List<User> userList = userRepository.findAll();
    userRepository.deleteAll(userList);
    System.out.println(userList);
    RestControllerResult<Boolean> result = new RestControllerResult<>();
    result.setSuccess(true);
    result.setData(true);
    return result;
  }


  @GetMapping("/find/{username}/{password}")
  public RestControllerResult<Boolean> find(
      @PathVariable String username, @PathVariable String password) {
    List<User> byUsernameAndPassword = userRepository.findByUsernameAndPassword(username, password);
    System.out.println(byUsernameAndPassword);
    userRepository.deleteAll(byUsernameAndPassword);
    System.out.println(byUsernameAndPassword);
    userRepository.saveAll(byUsernameAndPassword);
    RestControllerResult<Boolean> result = new RestControllerResult<>();
    result.setSuccess(true);
    result.setData(true);
    return result;
  }
}
